package com.yanqu.road.server.manager.activity.relation;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eBigRankType;
import com.yanqu.road.entity.rank.ServerRank;
import com.yanqu.road.entity.rank.UnionActivityRank;
import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.logic.bussiness.rank.RankBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.cross.CrossActivityRankListModel;
import com.yanqu.road.logic.cross.CrossActivityServerRankListModel;
import com.yanqu.road.logic.cross.CrossActivityUnionRankListModel;
import com.yanqu.road.logic.cross.CrossRankListModel;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.activity.CrossRelationActivityMgr;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossRelationRankMgr extends TempMgr {


    private static Map<Integer, CrossActivityRankListModel> relationRankListModelMap;


    /**
     * 各个游戏服的个人排名 区服，活动，数据
     */
    private static Map<Long, Map<Integer, CrossRankListModel>> allCrossRankListModelMap;

    private static Map<Integer, CrossActivityServerRankListModel> relationServerRankListModelMap;

    private static Map<Integer, CrossActivityUnionRankListModel> relationUnionRankListModelMap;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for(CrossActivityRankListModel rankListModel : relationRankListModelMap.values()){
            if(rankListModel.isUpdate()){
                rankListModel.saveCrossRelationRankList();
            }
        }
        for(CrossActivityUnionRankListModel rankListModel : relationUnionRankListModelMap.values()){
            if(rankListModel.isUpdate()){
                rankListModel.saveCrossRelationUnionRankList();
            }
        }
        //所有区服的数据
        for(Map<Integer, CrossRankListModel> dataMap : allCrossRankListModelMap.values()) {
            for (CrossRankListModel rankListModel : dataMap.values()) {
                rankListModel.saveActivityRankList();
            }
        }

        for(CrossActivityServerRankListModel model : relationServerRankListModelMap.values()) {
            model.saveRelation();
        }
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        allCrossRankListModelMap = new ConcurrentHashMap<>();
        initAllCrossRankListModelMap();
        relationServerRankListModelMap = new ConcurrentHashMap<>();
        initCrossServerRankListModelMap2();

        relationRankListModelMap = new ConcurrentHashMap<>();
        initCrossRankListModelMap();
        relationUnionRankListModelMap = new ConcurrentHashMap<>();
        initCrossUnionRankListModelMap();
        return true;
    }


    public static int getMaxRank(ActivityInfo activityInfo) {
        int maxRank = 0;
        if(!StringUtils.isNullOrEmpty(activityInfo.getParam6())){
            maxRank = Integer.parseInt(activityInfo.getParam6());
        }
        int conditionType = ActivityHelper.getCrossRankConditionType(activityInfo.getType(), activityInfo.getChildType());
        int maxRank2 = ActivityHelper.getMaxRankByConditionType(conditionType, ActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
        if (maxRank2 > maxRank) {
            maxRank = maxRank2;
        }
        if (maxRank <= 0) {
            maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
        }
        return maxRank;
    }

    private static Map<Integer, CrossRankListModel> getCrossRankListModelMap(long serverId){
        return allCrossRankListModelMap.get(serverId);
    }

    public static CrossRankListModel getCrossRankListModel(long serverId, int activityId){
        Map<Integer, CrossRankListModel> modelMap  = getCrossRankListModelMap(serverId);
        if(null != modelMap){
            return modelMap.get(activityId);
        }
        return null;
    }

    //原先的冲榜只能100人，凉凉，要全服
    private void initCrossServerRankListModelMap(){
        Map<Integer, ActivityInfo> activityInfoMap = CrossRelationActivityMgr.getOpenActivityInfoMap();
        synchronized (relationServerRankListModelMap){
            for (ActivityInfo activityInfo : activityInfoMap.values()) {
                CrossActivityRankListModel crossActivityRankListModel = new CrossActivityRankListModel(activityInfo.getActivityId(), false);
                CrossActivityServerRankListModel crossActivityServerRankListModel = new CrossActivityServerRankListModel(activityInfo.getActivityId());
                int conditionType = ActivityHelper.getCrossRankConditionType(activityInfo.getType(), activityInfo.getChildType());
                int maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, ActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                if(maxRank <= 0){
                    maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
                }
                crossActivityRankListModel.setRankNum(maxRank);
                LinkedList<CrossUserRank> userRankList = new LinkedList<>();
                LinkedList<ServerRank> serverRankList = new LinkedList<>();
                for(long serverId : activityInfo.getServerIdList()){
                    ServerRank serverRank = new ServerRank();
                    serverRank.setServerId(serverId);
                    BigInteger value = BigInteger.ZERO;
                    CrossRankListModel tempModel = getCrossRankListModel(serverId,activityInfo.getActivityId());
                    if(null != tempModel){
                        LinkedList<CrossUserRank> tempUserRankList = tempModel.getRankList();
                        for(CrossUserRank tempRank : tempUserRankList){
                            userRankList.add(tempRank.clone());
                        }
                        //只取区服前100名参与区服总分
                        int tempRank = Integer.parseInt(activityInfo.getParam6());
                        if(tempRank > 0){
                            while (tempUserRankList.size() > tempRank){
                                tempUserRankList.removeLast();
                            }
                        }
                        for(CrossUserRank userRank : tempUserRankList){
                            value = value.add(userRank.getValue());
                        }
                    }
                    serverRank.setValue(value);
                    serverRankList.add(serverRank);
                }
                crossActivityRankListModel.setRankList(userRankList);
                crossActivityServerRankListModel.setRankList(serverRankList);
//                crossActivityRankListModelMap.put(activityInfo.getActivityId(), crossActivityRankListModel);
                relationServerRankListModelMap.put(activityInfo.getActivityId(), crossActivityServerRankListModel);
            }
        }
    }

    private void initCrossServerRankListModelMap2(){
        Map<Integer, ActivityInfo> activityInfoMap = CrossRelationActivityMgr.getOpenActivityInfoMap();
        synchronized (relationServerRankListModelMap){
            List<Integer> activityIdList = new ArrayList<>(activityInfoMap.keySet());
            Map<Integer,LinkedList<ServerRank>> crossUserRankListMap = RankBussiness.getCrossServerRankListMap(activityIdList);
            for (ActivityInfo activityInfo : activityInfoMap.values()) {
                CrossActivityRankListModel crossActivityRankListModel = new CrossActivityRankListModel(activityInfo.getActivityId(), false);
                CrossActivityServerRankListModel crossActivityServerRankListModel = new CrossActivityServerRankListModel(activityInfo.getActivityId());
                int conditionType = ActivityHelper.getCrossRankConditionType(activityInfo.getType(), activityInfo.getChildType());
                int maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, ActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                if(maxRank <= 0){
                    maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
                }
                crossActivityRankListModel.setRankNum(maxRank);
                LinkedList<CrossUserRank> userRankList = new LinkedList<>();
                LinkedList<ServerRank> serverRankList = new LinkedList<>();
                if(crossUserRankListMap.containsKey(activityInfo.getActivityId())){
                    LinkedList<ServerRank> checkServerRankList = crossUserRankListMap.get(activityInfo.getActivityId());
                    //重复的去掉
                    Map<Long,ServerRank> checkMap = new ConcurrentHashMap<>();
                    for(ServerRank serverRank : checkServerRankList){
                        if(checkMap.containsKey(serverRank.getServerId())){
                            if(checkMap.get(serverRank.getServerId()).getValue().compareTo(serverRank.getValue()) < 0){
                                checkMap.put(serverRank.getServerId(),serverRank);
                            }
                        }else{
                            checkMap.put(serverRank.getServerId(),serverRank);
                        }
                    }
                    serverRankList = new LinkedList<>(checkMap.values());
                }else{
                    for(long serverId : activityInfo.getServerIdList()){
                        ServerRank serverRank = new ServerRank();
                        serverRank.setServerId(serverId);
                        BigInteger value = BigInteger.ZERO;
                        serverRank.setValue(value);
                        serverRankList.add(serverRank);
                    }
                }
                crossActivityRankListModel.setRankList(userRankList);
                crossActivityServerRankListModel.setRankList(serverRankList);
//                crossActivityRankListModelMap.put(activityInfo.getActivityId(), crossActivityRankListModel);
                relationServerRankListModelMap.put(activityInfo.getActivityId(), crossActivityServerRankListModel);
            }
        }
    }
    private void initAllCrossRankListModelMap(){
        Map<Integer, ActivityInfo> activityInfoMap = CrossRelationActivityMgr.getOpenActivityInfoMap();
        synchronized (allCrossRankListModelMap){
            List<Integer> activityIdList = new ArrayList<>(activityInfoMap.keySet());
            Map<Long, Map<Integer, LinkedList<CrossUserRank>>> crossUserRankListMap = RankBussiness.getCrossActivityRankListMap(activityIdList);
            for(Map.Entry<Long, Map<Integer, LinkedList<CrossUserRank>>> dataEntry : crossUserRankListMap.entrySet()){
                for(Map.Entry<Integer, LinkedList<CrossUserRank>> tempEntry : dataEntry.getValue().entrySet()) {
                    CrossRankListModel rankListModel = new CrossRankListModel(dataEntry.getKey(), tempEntry.getKey(), eBigRankType.Normal.getValue());
                    ActivityInfo activityInfo = activityInfoMap.get(tempEntry.getKey());
                    int maxRank = getMaxRank(activityInfo);
                    rankListModel.setRankNum(maxRank);
                    rankListModel.setRankList(tempEntry.getValue());
                    Map<Integer, CrossRankListModel> modelMap = getCrossRankListModelMap(dataEntry.getKey());
                    if(null == modelMap){
                        modelMap = new ConcurrentHashMap<>();
                        allCrossRankListModelMap.put(dataEntry.getKey(), modelMap);
                    }
                    modelMap.put(tempEntry.getKey(), rankListModel);
                }
            }
        }

    }

    private void initCrossRankListModelMap(){
        synchronized (relationRankListModelMap) {
            Map<Integer, ActivityInfo> activityInfoMap = CrossRelationActivityMgr.getOpenActivityInfoMap();
            List<Integer> activityIdList = new ArrayList<>();
            for (ActivityInfo activityInfo : activityInfoMap.values()) {
                activityIdList.add(activityInfo.getActivityId());
            }
            Map<Integer, LinkedList<CrossUserRank>> crossUserRankListMap = RankBussiness.getCrossRelationRankListMap(activityIdList);
            for (Map.Entry<Integer, LinkedList<CrossUserRank>> dataEntry : crossUserRankListMap.entrySet()) {
                CrossActivityRankListModel rankListModel = new CrossActivityRankListModel(dataEntry.getKey(), true);
                ActivityInfo activityInfo = activityInfoMap.get(dataEntry.getKey());
                int conditionType = CrossRelationActivityMgr.getEventConditionType(dataEntry.getKey(),CrossRelationActivityMgr.EVENT_RANK_USER_TYPE);
                int maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, CrossRelationActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                if (maxRank <= 0) {
                    maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
                }
                rankListModel.setRankNum(maxRank);
                rankListModel.setRankList(dataEntry.getValue());
                relationRankListModelMap.put(dataEntry.getKey(), rankListModel);
            }
        }
    }

    private void initCrossUnionRankListModelMap(){
        synchronized (relationUnionRankListModelMap) {
            Map<Integer, ActivityInfo> activityInfoMap = CrossRelationActivityMgr.getOpenActivityInfoMap();
            List<Integer> activityIdList = new ArrayList<>();
            for (ActivityInfo activityInfo : activityInfoMap.values()) {
                activityIdList.add(activityInfo.getActivityId());
            }
            Map<Integer, LinkedList<UnionActivityRank>> crossUnionRankListMap = RankBussiness.getCrossRelationUnionRankListMap(activityIdList);
            for (Map.Entry<Integer, LinkedList<UnionActivityRank>> dataEntry : crossUnionRankListMap.entrySet()) {
                CrossActivityUnionRankListModel rankListModel = new CrossActivityUnionRankListModel(dataEntry.getKey());
                ActivityInfo activityInfo = activityInfoMap.get(dataEntry.getKey());
                int conditionType = CrossRelationActivityMgr.getEventConditionType(dataEntry.getKey(),CrossRelationActivityMgr.EVENT_RANK_UNION_TYPE);
                int maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, CrossRelationActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                if (maxRank <= 0) {
                    maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
                }
                rankListModel.setRankNum(maxRank);
                rankListModel.setRankList(dataEntry.getValue());
                relationUnionRankListModelMap.put(dataEntry.getKey(), rankListModel);
            }
        }
    }

    public static CrossActivityRankListModel getCrossActivityRankListModel(int activityId){
        return relationRankListModelMap.get(activityId);
    }

    public static CrossActivityServerRankListModel getCrossActivityServerRankListModel(int activityId){
        return relationServerRankListModelMap.get(activityId);
    }

    public static CrossActivityUnionRankListModel getCrossActivityUnionRankListModel(int activityId){
        return relationUnionRankListModelMap.get(activityId);
    }

    public static void changeRelationRank(int activityId, CrossUserRank crossUserRank){
        CrossActivityRankListModel rankListModel = getCrossActivityRankListModel(activityId);
        if(null == rankListModel){
            synchronized (relationRankListModelMap){
                if(!relationRankListModelMap.containsKey(activityId)){
                    ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
                    CrossRelationActivityMgr.loadActivity(activityInfo);
                    if(null != activityInfo){
                        CrossActivityRankListModel crossActivityRankListModel = new CrossActivityRankListModel(activityInfo.getActivityId(), true);
                        int conditionType = CrossRelationActivityMgr.getEventConditionType(activityId,CrossRelationActivityMgr.EVENT_RANK_USER_TYPE);
                        int maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, CrossRelationActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                        if(maxRank <= 0){
                            maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
                        }
                        crossActivityRankListModel.setRankNum(maxRank);
                        relationRankListModelMap.put(activityId, crossActivityRankListModel);
                    }
                }
            }
            rankListModel = getCrossActivityRankListModel(activityId);
        }
        if(null != rankListModel){
            rankListModel.rankChange(crossUserRank);
        }
    }
    /**
     * 更新各个区服副本排行
     */
    public static void changeUserRank(int activityId, CrossUserRank crossUserRank){
        long serverId = crossUserRank.getUserBaseInfo().getServerId();
        if(0 == serverId){
            return;
        }
        CrossRankListModel rankListModel = getCrossRankListModel(serverId, activityId);
        if (null == rankListModel) {
            synchronized (allCrossRankListModelMap) {
                if(!allCrossRankListModelMap.containsKey(serverId)){
                    allCrossRankListModelMap.put(serverId, new ConcurrentHashMap<>());
                }
                if (!allCrossRankListModelMap.get(serverId).containsKey(activityId)) {
                    rankListModel = new CrossRankListModel(serverId, activityId, eBigRankType.Normal.getValue());
                    ActivityInfo activityInfo = ActivityMgr.getActivityInfo(activityId);
                    int maxRank = 0;
                    if(null != activityInfo) {
                        maxRank = Integer.parseInt(activityInfo.getParam6());
                        int conditionType = ActivityHelper.getCrossRankConditionType(activityInfo.getType(), activityInfo.getChildType());
                        int maxRank2 = ActivityHelper.getMaxRankByConditionType(conditionType, ActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                        if (maxRank2 > maxRank) {
                            maxRank = maxRank2;
                        }
                    }
                    if(maxRank <= 0){
                        maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
                    }
                    rankListModel.setRankNum(maxRank);
                    allCrossRankListModelMap.get(serverId).put(activityId, rankListModel);
                }
            }
            rankListModel = getCrossRankListModel(serverId, activityId);
        }
        if (null != rankListModel) {
            rankListModel.rankChange(crossUserRank);
            LinkedList<CrossUserRank> userRankList = rankListModel.getRankList();
            //只取区服前100名参与区服总分
            int tempRank = 0;
            ActivityInfo activityInfo = ActivityMgr.getActivityInfo(activityId);
            if(null != activityInfo) {
                tempRank = Integer.parseInt(activityInfo.getParam6());
            }
            if(tempRank > 0){
                while (userRankList.size() > tempRank){
                    userRankList.removeLast();
                }
            }
            ServerRank serverRank = new ServerRank();
            serverRank.setServerId(serverId);
            BigInteger value = BigInteger.ZERO;
            for(CrossUserRank userRank : userRankList){
                if (userRank.getValue().compareTo(BigInteger.ZERO) > 0) {
                    value = value.add(userRank.getValue());
                }
            }
            serverRank.setValue(value);
            changeRelationServerRank(activityId, serverRank);
        }
    }

    public static void changeRelationServerRank(int activityId, ServerRank serverRank){
        CrossActivityServerRankListModel rankListModel = getCrossActivityServerRankListModel(activityId);
        if (null == rankListModel) {
            synchronized (relationServerRankListModelMap) {
                if(!relationServerRankListModelMap.containsKey(activityId)){
                    ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
                    CrossRelationActivityMgr.loadActivity(activityInfo);
                    if(null != activityInfo) {
                        rankListModel = new CrossActivityServerRankListModel(activityId);
                        LinkedList<ServerRank> serverRankList = new LinkedList<>();
                        for(long serverId : activityInfo.getServerIdList()){
                            ServerRank tempRank = new ServerRank();
                            tempRank.setServerId(serverId);
                            tempRank.setValue(BigInteger.ZERO);
                            serverRankList.add(tempRank);
                        }
                        rankListModel.setRankList(serverRankList);
                        relationServerRankListModelMap.put(activityId, rankListModel);
                    }
                }
            }
            rankListModel = getCrossActivityServerRankListModel(activityId);
        }
        if (null != rankListModel) {
            rankListModel.rankChange(serverRank);
        }
    }

    public static void changeRelationUnionRank(int activityId, UnionActivityRank unionRank,boolean isUnionDel){
        CrossActivityUnionRankListModel rankListModel = getCrossActivityUnionRankListModel(activityId);
        if(null == rankListModel){
            synchronized (relationUnionRankListModelMap){
                if(!relationUnionRankListModelMap.containsKey(activityId)){
                    ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
                    CrossRelationActivityMgr.loadActivity(activityInfo);
                    if(null != activityInfo){
                        CrossActivityUnionRankListModel crossActivityUnionRankListModel = new CrossActivityUnionRankListModel(activityInfo.getActivityId());
                        int conditionType = CrossRelationActivityMgr.getEventConditionType(activityId,CrossRelationActivityMgr.EVENT_RANK_UNION_TYPE);
                        int maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, CrossRelationActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                        if(maxRank <= 0){
                            maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
                        }
                        crossActivityUnionRankListModel.setRankNum(maxRank);
                        relationUnionRankListModelMap.put(activityId, crossActivityUnionRankListModel);
                    }
                }
            }
            rankListModel = getCrossActivityUnionRankListModel(activityId);
        }
        if(null != rankListModel){
            if(isUnionDel){
                rankListModel.removeRank(unionRank.getUnionUid());
            }else {
                rankListModel.rankChange(unionRank);
            }
        }
    }

    public static CrossUserRank getCrossActivityRankInfo(int activityId, long serverId, long userId) {
        CrossActivityRankListModel rankListModel = getCrossActivityRankListModel(activityId);
        if(rankListModel == null){
            return null;
        }
        return rankListModel.getMyRankInfo(userId,serverId);
    }

    public static int getCrossActivityRank(int activityId, long serverId, long userId) {
        int rank = -1;
        CrossActivityRankListModel rankListModel = getCrossActivityRankListModel(activityId);
        if(null != rankListModel){
            rank = rankListModel.getMyRank(userId, serverId);
        }
        int maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
        ActivityInfo activityInfo = CrossRelationActivityMgr.getOpenActivityInfo(activityId);
        if(null != activityInfo) {
            int conditionType = CrossRelationActivityMgr.getEventConditionType(activityId,CrossRelationActivityMgr.EVENT_RANK_USER_TYPE);
            maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, CrossRelationActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
        }
        if(rank > maxRank){
            rank = -1;
        }
        return rank;
    }

    public static int getCrossActivityServerRank(int activityId, long serverId, long userId) {
        int rank = -1;
        CrossActivityServerRankListModel rankListModel = getCrossActivityServerRankListModel(activityId);
        if(null != rankListModel){
            rank = rankListModel.getMyRank(serverId);
        }
        int maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
        ActivityInfo activityInfo = CrossRelationActivityMgr.getOpenActivityInfo(activityId);
        if(null != activityInfo) {
            int conditionType = CrossRelationActivityMgr.getEventConditionType(activityId,CrossRelationActivityMgr.EVENT_RANK_SERVER_TYPE);
            maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, CrossRelationActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
        }
        if(rank > maxRank){
            rank = -1;
        }
        return rank;
    }

    public static int getCrossActivityUnionRank(int activityId, long serverId, String unionUid) {
        int rank = -1;
        CrossActivityUnionRankListModel rankListModel = getCrossActivityUnionRankListModel(activityId);
        if(null != rankListModel){
            rank = rankListModel.getMyRank(serverId, unionUid);
        }
        int maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
        ActivityInfo activityInfo = CrossRelationActivityMgr.getOpenActivityInfo(activityId);
        if(null != activityInfo) {
            int conditionType = CrossRelationActivityMgr.getEventConditionType(activityId,CrossRelationActivityMgr.EVENT_RANK_UNION_TYPE);
            maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, CrossRelationActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
        }
        if(rank > maxRank){
            rank = -1;
        }
        return rank;
    }
}